<?php
/*
 * 调用人人网API接口类，本类需要继承restClient类方可使用
 * 要求最低的PHP版本是5.2.0，并且还要支持以下库：cURL, Libxml 2.6.0
 * This example for invoke RenRen RESTful Webservice
 * It MUST be extends RESTClient
 * The requirement of PHP version is 5.2.0 or above, and support as below:
 * cURL, Libxml 2.6.0
 *
 * @Xweibo (C)1996-2099 SINA Inc.
 * @Created: 0:11:39 2011/8/30
 * @Author:	liwen<liwen2@staff.sina.com.cn>
 */

require_once 'renrenClient.class.php';

class renrenWeibo_class 
{
	private $obj;
	
	function __construct(){
		$this->obj = new renrenClient();
	}
	
	function throwException($result)
	{
		$result['error_description'] = isset($result['error_description']) ? $result['error_description'] : '';
		switch ($result['error']) {
			case 'invalid_grant':
				$msg = array(
					'error_code' => '1510001',
					'error' => $result['error'].':'.$result['error_description']
				);
			break;				
			default:
				$msg = array(
					'error_code' => '1510001',
					'error' => 'unknow system error  api: ' . $result['error'].':'.$result['error_description']
				);					
		}
		return $msg;
	}		
	
	/*
	 * 获取授权的url
	 * @params url 回调地址
	 */
	function getAuthorizeURL($url, $display='page') {
		$display = 'mobile'==$display ? 'touch' : $display;
		return "https://graph.renren.com/oauth/authorize?client_id=".$this->obj->_config['APIKey']."&response_type=code&redirect_uri=".urlencode($url)."&scope=publish_feed,read_user_blog,read_user_feed&display=$display";
	}
	
	/*
	 * 获取access_token
	 * @params url 回调地址
	 * @params code 授权返回的code
	 */
	function getAccessToken($code, $url) {
		$url = "https://graph.renren.com/oauth/token?grant_type=authorization_code&client_id=".$this->obj->_config['APIKey']."&client_secret=".$this->obj->_config['SecretKey']."&redirect_uri=".urlencode($url)."&code=".$code;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$result = curl_exec($ch);
				
		curl_close($ch);
		$result = json_decode(preg_replace('#(?<=[,\{\[])\s*("\w+"):(\d{6,})(?=\s*[,\]\}])#si', '${1}:"${2}"', $result), true);
		
        if (isset($result['error'])) {
			return  $this->throwException($result);
		}
		//设置access token
		$this->setToken($result['access_token']);	
		return $result;
	}
	
	
	/*
	 * 获取access_token
	 * @params $refreshToken refresh Token
	 */
	function refreshToken($refreshToken) 
	{
		$url = "https://graph.renren.com/oauth/token?grant_type=refresh_token&refresh_token={$refreshToken}&client_id=".$this->obj->_config['APIKey']."&client_secret=".$this->obj->_config['SecretKey'];
		$ch  = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		
		$result = curl_exec($ch);
		curl_close($ch);
		$result = json_decode(preg_replace('#(?<=[,\{\[])\s*("\w+"):(\d{6,})(?=\s*[,\]\}])#si', '${1}:"${2}"', $result), true);
		
        if (isset($result['error'])) {
			return  $this->throwException($result);
		}
		//设置access token
		$this->setToken($result['access_token']);	
		return $result;
	}
	
	
	/**
	 * 设置access_token
	 *
	 * @return
	 */
	function setToken($access_token)
	{
		$this->obj->setAccessToken($access_token);
	}	
	
	/*
	 * 获取用户信息
	 */
	function getUserInfo(){
		$error = array();
		$ret   = $this->obj->POST('users.getInfo');
		return $this->_dealResult($ret);
	}
	
	/*
	 * 发布微博到人人网feed中
	 * @params name string 标题
	 * @params description  string 内容
	 * @params url  标题连接地址
	 * @params image  图片地址
	 * return boolean
	 */
	function publishFeed($p) {	
		$error = array();
		$ret = $this->obj->POST('feed.publishFeed', $p);
		return $this->_dealResult($ret);
	}
	
	
	/**
	 * 获取当前登录用户的好友列表
	 * @param page	int	分页，默认为1
	 * @param count	int	返回每页个数，默认为500
	 */
	function getFriends($p)
	{
		$error = array();
		$ret   = $this->obj->POST('friends.getFriends', $p);
		return $this->_dealResult($ret);
	}
	
	
	/**
	 * 返回App好友的ID列表
	 * @param $p
	 */
	function getAppFriends()
	{
		$error = array();
		$ret   = $this->obj->POST('friends.getAppUsers');
		return $this->_dealResult($ret);
	}
	
	
	/**
	 * 获取人人日志列表
	 */
	function getStatus($p)
	{
		$error = array();
		$ret   = $this->obj->POST('feed.get', $p);
		return $this->_dealResult($ret);
	}
	
	/**
	 * 搜索用户
	 * @param array $p
	 *   name:搜索姓名
		 uid:搜索人人网ID
		 email:搜索注册邮箱(name,uid,email至少选择一个)
		 condition:查询条件。json格式如：[{"t":"base","gend":"男生","prov":"天津"}
		 page: 页码
		 count:每页显示的日志的数量, 缺省值为20
	 */
	function searchFriendds($p)
	{
		$error = array();
		$ret   = $this->obj->POST('friends.search', $p);
		return $this->_dealResult($ret);
	}
	
	/**
	 * 批量获取用户信息
	 * @param array $p uids:用户ID
	 */
	function batchGetUser($p)
	{
		$error = array();
		$ret   = $this->obj->POST('users.getInfo', $p);
		return $this->_dealResult($ret);
	}
	
	
	/**
	 * 调用人人API
	 * @param $route， 人人API的路由
	 * @param $p，参数
	 */
	function call($route, $p)
	{
		$error = array();
		$ret   = $this->obj->POST($route, $p);
		return $this->_dealResult($ret);
	}
	

	/**
	 * 处理结果
	 * @param $ret
	 */
	function _dealResult($ret, $return=FALSE)
	{
		if(is_object($ret) && isset($ret->error_code)) {
			$error['error'] = $ret->error_code.':'.$ret->error_msg;
			return  $this->throwException($error);
		}
		
		if(is_array($ret) && isset($ret['error_code'])) {
			$error['error'] = $ret['error_code'].':'.$ret['error_msg'];
			return  $this->throwException($error);
		}
		return $return===FALSE ? $ret : $return;
	}
}
